#!/bin/bash

devname=""
workingpath=$(pwd)
Qthreshold=0
Dthreshold=0

usage="\
	Usage:
./find_exceed_queue.sh [-d devname] [-p path] [-Q threshold] [-D threshold] [-h]
COMMAND-LINE Options:
-d	./find_exceed_queue.sh 脚本将要跳转过去的工作目录
-Q	IO Q2C（表示io Queued To Complete）耗时的阈值，支持浮点表示，单位为秒
-D	IO D2C（表示io Dispatched/Issued To Complete）耗时的阈值 ，支持浮点表示，单位为秒
-h	显示./find_exceed_queue.sh的用法
"
while getopts 'd:p:Q:D:h' OPT; do
	case $OPT in
		d)      devname="$OPTARG"    
			;;
		p)      workingpath="$OPTARG"    
			;;
		Q)      Qthreshold="$OPTARG"
			;;
		D)	Dthreshold="$OPTARG"
			;;
		h)      echo "$usage"
			exit $?
			;;
		?)      echo "Invalid option: $OPT" >&2
			echo "$usage"
			exit 1
			;;
	esac
done

cd "$workingpath"

if [ ! -e blktrace.txt ]; then
	blkparse -i $devname -o blktrace.txt 1>/dev/null
fi

safe_rm *_without_C_sectors.txt *2C_exceed_sectors.txt *2C_exceed_blktrace.txt 2>/dev/null

grep "C   " blktrace.txt > queue_C.txt

if [[ $Qthreshold != 0 ]]; then
	grep "Q   " blktrace.txt > queue_Q.txt
	while read line
	do
		Qsector=$( echo $line | awk '{ print $8 }'  )
		Qtime=$( echo $line | awk '{ print $4 }'  )
		Csectorline=$( grep $Qsector queue_C.txt )
		Csector=$( echo $Csectorline | awk '{ print $8 }' )
		if [ -z $Csector ]; then
			echo $Qsector >> Q_without_C_sectors.txt
			continue
		fi

		Ctime=$( echo $Csectorline | awk '{ print $4 }' )
		Q2Ctime=$( echo "$Ctime - $Qtime" | bc )
		if [ $(echo "$Q2Ctime > $Qthreshold" | bc) -ne 0 ]; then
			echo $Qsector >> Q2C_exceed_sectors.txt
			grep $Qsector blktrace.txt >> Q2C_exceed_blktrace.txt
			echo "" >> Q2C_exceed_blktrace.txt	
		fi
	done < queue_Q.txt
	echo "" ; echo "****************************Q2C Exceed IO****************************"
	cat Q2C_exceed_blktrace.txt 2>/dev/null
fi

if [[ $Dthreshold != 0 ]]; then
	grep "D   " blktrace.txt > queue_D.txt
	while read line
	do
		Dsector=$( echo $line | awk '{ print $8 }'  )
		Dtime=$( echo $line | awk '{ print $4 }'  )
		Csectorline=$( grep $Dsector queue_C.txt )
		Csector=$( echo $Csectorline | awk '{ print $8 }' )
		if [ -z $Csector ]; then
			echo $Dsector >> D_without_C_sectors.txt
			continue
		fi

		Ctime=$( echo $Csectorline | awk '{ print $4 }' )
		D2Ctime=$( echo "$Ctime - $Dtime" | bc )
		if [ $(echo "$D2Ctime > $Dthreshold" | bc) -ne 0 ]; then
			echo $Dsector >> D2C_exceed_sectors.txt
			grep $Dsector blktrace.txt >> D2C_exceed_blktrace.txt
			echo "" >> D2C_exceed_blktrace.txt	
		fi
	done < queue_D.txt
	echo "" ; echo "****************************D2C Exceed IO****************************"
	cat D2C_exceed_blktrace.txt 2>/dev/null
fi
echo "**************************Get Exceed IO End**************************"
